package com.liangxy.news.ui.main.home;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.liangxy.news.R;
import com.liangxy.news.model.News;
import com.liangxy.news.repository.NewsRepository;
import com.liangxy.news.util.SharedPreferencesManager;

import java.util.ArrayList;
import java.util.List;

/**
 * Fragment to display news list for a specific category
 */
public class NewsCategoryFragment extends Fragment implements HomeFragment.NewsLoadCallback {
    
    private static final String TAG = "NewsCategoryFragment";
    private static final String ARG_CATEGORY = "category";
    
    private String category;
    private RecyclerView rvNewsList;
    private ProgressBar progressBar;
    private TextView tvNoData;
    private SwipeRefreshLayout swipeRefreshLayout;
    private Button btnRetry;
    
    private NewsAdapter newsAdapter;
    private NewsRepository newsRepository;
    private SharedPreferencesManager preferencesManager;
    private String currentUserId;
    
    /**
     * Create a new instance of NewsCategoryFragment
     * @param category News category
     * @return NewsCategoryFragment instance
     */
    public static NewsCategoryFragment newInstance(String category) {
        NewsCategoryFragment fragment = new NewsCategoryFragment();
        Bundle args = new Bundle();
        args.putString(ARG_CATEGORY, category);
        fragment.setArguments(args);
        return fragment;
    }
    
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            category = getArguments().getString(ARG_CATEGORY);
        }
        
        // 初始化新闻仓库
        newsRepository = NewsRepository.getInstance(requireContext());
        
        // 初始化SharedPreferencesManager
        preferencesManager = new SharedPreferencesManager(requireContext());
        
        // 获取当前用户ID
        currentUserId = preferencesManager.getCurrentUserId();
    }
    
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_news_category, container, false);
        
        // Initialize components
        rvNewsList = view.findViewById(R.id.rvNewsList);
        progressBar = view.findViewById(R.id.progressBar);
        tvNoData = view.findViewById(R.id.tvNoData);
        swipeRefreshLayout = view.findViewById(R.id.swipeRefreshLayout);
        btnRetry = view.findViewById(R.id.btnRetry);
        
        // Setup recycler view
        rvNewsList.setLayoutManager(new LinearLayoutManager(requireContext()));
        newsAdapter = new NewsAdapter(new ArrayList<>());
        newsAdapter.setNewsRepository(newsRepository, currentUserId);
        rvNewsList.setAdapter(newsAdapter);
        
        // Setup swipe refresh
        swipeRefreshLayout.setOnRefreshListener(this::loadNews);
        swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary);
        
        // Setup retry button
        btnRetry.setOnClickListener(v -> loadNews());
        
        return view;
    }
    
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        
        // Load news
        loadNews();
    }
    
    /**
     * Load news for the category
     */
    private void loadNews() {
        Log.d(TAG, "Loading news for category: " + category);
        showLoading();
        
        // Get parent fragment
        Fragment parentFragment = getParentFragment();
        if (parentFragment instanceof HomeFragment) {
            // Call parent fragment to load news
            ((HomeFragment) parentFragment).loadNews(category, this);
        } else {
            showError("无法加载新闻");
        }
    }
    
    /**
     * Show loading state
     */
    private void showLoading() {
        progressBar.setVisibility(View.VISIBLE);
        tvNoData.setVisibility(View.GONE);
        btnRetry.setVisibility(View.GONE);
        rvNewsList.setVisibility(View.GONE);
        
        // 确保SwipeRefreshLayout显示刷新状态
        if (!swipeRefreshLayout.isRefreshing()) {
            swipeRefreshLayout.setRefreshing(true);
        }
    }
    
    /**
     * Show error message
     * @param message Error message
     */
    private void showError(String message) {
        swipeRefreshLayout.setRefreshing(false);
        progressBar.setVisibility(View.GONE);
        rvNewsList.setVisibility(View.GONE);
        tvNoData.setVisibility(View.VISIBLE);
        tvNoData.setText(message);
        btnRetry.setVisibility(View.VISIBLE);
    }
    
    /**
     * Show news list
     * @param newsList News list to show
     */
    private void showNewsList(List<News> newsList) {
        swipeRefreshLayout.setRefreshing(false);
        progressBar.setVisibility(View.GONE);
        tvNoData.setVisibility(View.GONE);
        btnRetry.setVisibility(View.GONE);
        rvNewsList.setVisibility(View.VISIBLE);
        newsAdapter.updateData(newsList);
    }
    
    @Override
    public void onNewsLoaded(List<News> newsList) {
        Log.d(TAG, "News loaded for category " + category + ": " + newsList.size() + " items");
        if (isAdded()) {
            showNewsList(newsList);
        }
    }
    
    @Override
    public void onNewsLoadFailed(String errorMessage) {
        Log.e(TAG, "Failed to load news for category " + category + ": " + errorMessage);
        if (isAdded()) {
            showError(errorMessage);
        }
    }
} 